package com.sx.gongzhong.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.sx.gongzhong.BaseActivity;
import com.sx.gongzhong.MyApplication;
import com.sx.gongzhong.R;
import com.sx.gongzhong.adapter.ExposureReplyAdapter;
import com.sx.gongzhong.adapter.ImageAdapter;
import com.sx.gongzhong.adapter.viewholder.ExposureHeadView;
import com.sx.gongzhong.model.CommentBean;
import com.sx.gongzhong.model.ExposureDetailBean;
import com.sx.gongzhong.model.PublicBean;
import com.sx.gongzhong.model.PublicTotalBean;
import com.sx.gongzhong.net.ServiceFactory;
import com.sx.gongzhong.pest.ExposureDetailPest;
import com.sx.gongzhong.pest.ReportAndForbiddenPest;
import com.sx.gongzhong.utils.BaseUtil;
import com.sx.gongzhong.utils.InitData;
import com.sx.gongzhong.utils.ToastUtils;
import com.sx.gongzhong.view.IExposureDetailView;
import com.sx.gongzhong.view.IVoidView;
import com.sx.gongzhong.widget.CustomDialog;
import com.sx.gongzhong.widget.LoadDialog;
import com.sx.gongzhong.widget.MyPopupWindow;
import com.sx.gongzhong.widget.ReportDialog;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import xiaofei.library.datastorage.DataStorageFactory;
import xiaofei.library.datastorage.IDataStorage;

import static com.sx.gongzhong.R.id.tv_Praise;

/**
 * 爆料详情
 */
public class ExposureDetailActivity extends BaseActivity implements View.OnClickListener
        , IExposureDetailView, IVoidView {
    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.et_Comment)
    EditText et_Comment;
    @BindView(R.id.rl_et_comment)
    RelativeLayout rlEtComment;
    private MyPopupWindow popupWindow;
    private String exposureID = "";
    private ExposureDetailBean detailBean;
    private IDataStorage dataStorage;
    private ReportAndForbiddenPest reportAndForbiddenPest;
    private ExposureDetailPest exposurePest;
    private ExposureReplyAdapter replyAdapter;
    private List<CommentBean> replyBeanList = new ArrayList<>();
    private int currentPager = 1;
    private ExposureHeadView exposureHeadView;

    @Override
    public void setUI(Bundle savedInstanceState) {
        setContentView(R.layout.recy_edit);
        ButterKnife.bind(this);
        setTitleName(R.string.exposure_detail);
        setRightImage(R.mipmap.icon_nav_more);
        exposureID = getIntent().getStringExtra("ExposureID");
        reportAndForbiddenPest = new ReportAndForbiddenPest(this);
        exposurePest = new ExposureDetailPest(this);
        initView();
    }


    private void initView() {
        rlEtComment.setVisibility(View.VISIBLE);
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setEnabled(false);
        }
        dataStorage = DataStorageFactory.getInstance(
                getApplicationContext(),
                DataStorageFactory.TYPE_DATABASE);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        replyAdapter = new ExposureReplyAdapter(this, R.layout.item_commont_list, replyBeanList);
        replyAdapter.setEmptyView(View.inflate(this, R.layout.no_comment_view, null));
        View view = LayoutInflater.from(this).inflate(R.layout.head_exposure_view, null);
        exposureHeadView = new ExposureHeadView();
        ButterKnife.bind(exposureHeadView, view);
        replyAdapter.addHeaderView(view);
        replyAdapter.setHeaderAndEmpty(true);
        replyAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                currentPager++;
                loadReplyList();
            }
        }, recyclerView);
        recyclerView.setAdapter(replyAdapter);
        exposureHeadView.tv_Praise.setOnClickListener(this);
        findViewById(R.id.imv_Right).setOnClickListener(this);
        et_Comment.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View arg0, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER &&
                        event.getAction() == KeyEvent.ACTION_DOWN) {
                    replyExposure();
                }
                return false;
            }
        });
        if (!BaseUtil.isEmpty(exposureID)) {
            LoadDialog.show(this, "加载中...");
            exposurePest.loadExposureDetail(exposureID);
            onRefresh();
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imv_Right:
                if (MyApplication.instance.userBean == null) {//未登录
                    startActivity(new Intent(this, LoginActivity.class));
                } else {
                    if (detailBean == null) {
                        ToastUtils.showToast(this, "网络异常 稍后再试");
                    } else {
                        createPop();
                    }
                }
                break;
            case R.id.tv_ShutUp://禁言
                createReport("forbiddenType", detailBean.getId(), "选择禁言时间","broke_news");
                popupWindow.dismiss();
                break;
            case R.id.tv_Report://举报
                createReport("reportType", detailBean.getId(), "选择举报类型","broke_news");
                popupWindow.dismiss();
                break;
            case R.id.tv_Delete://删除
                createDialog(detailBean.getId(), 1);
                popupWindow.dismiss();
                break;
            case R.id.tv_Cancel:
                popupWindow.dismiss();
                break;
            case tv_Praise://点赞
                if (MyApplication.instance.userBean == null) {//未登录
                    startActivity(new Intent(this, LoginActivity.class));
                } else {
                    if (!BaseUtil.isEmpty(exposureID)) {
                        exposurePest.praiseExposure(exposureID);
                    } else {
                        ToastUtils.showToast(this, "网络异常 稍后再试");
                    }
                }
                break;
        }
    }

    /**
     * @param type  类型
     * @param id    数据id
     * @param title 弹框id
     * @param columnType 举报模块
     */
    public void createReport(final String type, final String id, String title, final String columnType) {
        PublicTotalBean bean = dataStorage.load(PublicTotalBean.class, type);
        //获取到举报类型
        if (bean != null && bean.getChildren() != null) {
            ReportDialog.Builder builder = new ReportDialog.Builder(this);
            builder.setDataList(bean.getChildren()).setTitle(title)
                    .loadType(new ReportDialog.TypeCallback() {
                        @Override
                        public void backType(PublicBean publicBean) {
                            if ("reportType".equals(type)) {//举报
                                reportAndForbiddenPest.report(publicBean.getId(), columnType, id);
                            }
                            if ("forbiddenType".equals(type)) {//禁言
                                reportAndForbiddenPest.addForbidden(publicBean.getId(), columnType, id);
                            }
                        }
                    }).create().show();
        } else {
            new InitData(this).loadData();
            ToastUtils.showToast(this, "服务器异常 稍后再试");
        }
    }

    /**
     * 删除type=1 删除楼 2删除回复
     */
    public void createDialog(final String dataId, final int type) {
        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        CustomDialog dialog = builder.setMessage("确定要删除吗？").
                setBackButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).setConfirmButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                LoadDialog.show(ExposureDetailActivity.this, "正在删除");
                if (type == 1) {
                    exposurePest.deleteExposure(dataId);
                }
                if (type == 2) {
                    exposurePest.replyExposureDelete(dataId);
                }
                dialog.dismiss();
            }
        }).create();
        dialog.show();
    }


    /**
     * 显示操作弹窗
     */
    private void createPop() {
        try {
            if (popupWindow == null) {
                View view = LayoutInflater.from(this).inflate(R.layout.pop_comment, null);
                popupWindow = new MyPopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
                popupWindow.setTouchable(true);
                popupWindow.setOutsideTouchable(false);
                popupWindow.setBackgroundDrawable(new ColorDrawable(Color.alpha(128)));
                view.findViewById(R.id.tv_ShutUp).setOnClickListener(this);
                view.findViewById(R.id.tv_Report).setOnClickListener(this);
                view.findViewById(R.id.tv_Delete).setOnClickListener(this);
                view.findViewById(R.id.tv_Cancel).setOnClickListener(this);
                if ("general".equalsIgnoreCase(MyApplication.instance.userBean.userType.code)) {//普通用户
                    view.findViewById(R.id.tv_ShutUp).setVisibility(View.GONE);
                    if (!detailBean.getPublisher().getId().equals(MyApplication.instance.userBean.id)) {
                        //不是楼主
                        view.findViewById(R.id.tv_Delete).setVisibility(View.GONE);
                    }
                }
            }
            popupWindow.showAsDropDown(findViewById(R.id.toolbar));
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtils.showToast(this, "系统异常 稍后再试");
        }
    }

    /**
     * 发表评论
     */
    private void replyExposure() {
        if (MyApplication.instance.userBean == null) {//未登录
            startActivity(new Intent(ExposureDetailActivity.this, LoginActivity.class));
        } else {
            String content = et_Comment.getText().toString().trim();
            if (BaseUtil.isEmpty(content)) {
                ToastUtils.showToast(ExposureDetailActivity.this, "评论不能为空");
                return;
            }
            if (detailBean == null) {
                ToastUtils.showToast(ExposureDetailActivity.this, "服务器异常 请检查网络");
                return;
            } else {
                exposurePest.replyExposure(detailBean.getId(), content);
            }
        }
    }

    @Override
    public void showError(String message) {
        LoadDialog.dismiss(this);
        ToastUtils.showToast(this, message);

    }

    /**
     * 获取详情
     *
     * @param detailBean
     */
    @Override
    public void loadExposureDetail(ExposureDetailBean detailBean) {
        LoadDialog.dismiss(this);
        if (detailBean != null) {
            this.detailBean = detailBean;
            showViews();
        }
    }

    /**
     * 删除/点赞
     *
     * @param message
     */
    @Override
    public void deleteExposure(String message) {
        LoadDialog.dismiss(this);
        if ("删除成功".equals(message)) {
            ToastUtils.showToast(this, message);
            finish();
        } else if ("删除回复".equals(message)) {
            onRefresh();
        } else if ("评论成功".equals(message)) {
            ToastUtils.showToast(this, message);
            et_Comment.setText("");
            onRefresh();
        } else {
            exposureHeadView.tv_PraiseAdd.setVisibility(View.VISIBLE);
            Animation anim = AnimationUtils.loadAnimation(this, R.anim.praise);
            anim.setFillAfter(true);
            exposureHeadView.tv_PraiseAdd.startAnimation(anim);
            exposureHeadView.tv_Praise.setText(message);
        }
    }

    /**
     * 获取回复列表
     *
     * @param lists
     */
    @Override
    public void loadExposureReplyList(List<CommentBean> lists, int total) {
        if (currentPager == 1) {
            replyBeanList.clear();
            replyAdapter.setNewData(replyBeanList);
        }
        if (lists != null && lists.size() > 0) {
            replyBeanList.addAll(lists);
        }
        if (replyBeanList.size() >= total) {
            replyAdapter.loadMoreEnd();
        } else {
            replyAdapter.loadMoreComplete();
        }
        exposureHeadView.tv_CommentNum.setText("大众点评(" + total + ")");
        replyAdapter.notifyDataSetChanged();
    }


    /**
     * 显示数据
     */
    private void showViews() {
        if (detailBean != null){
            if (detailBean.getPublisher() != null) {
                if (!BaseUtil.isEmpty(detailBean.getPublisher().getHeaderUrl())){
                    Glide.with(this).load(ServiceFactory.getUrl(detailBean.getPublisher().getHeaderUrl()))
                            .apply(new RequestOptions().centerCrop().circleCrop().
                                    placeholder(R.mipmap.img_head_96).error(R.mipmap.img_head_96))
                            .into(exposureHeadView.im_Head);
                }else {
                    exposureHeadView.im_Head.setImageResource(R.mipmap.img_head_58);
                }
                exposureHeadView.tv_Name.setText(detailBean.getPublisher().getName());
            }else {
                exposureHeadView.im_Head.setImageResource(R.mipmap.img_head_58);
            }
            exposureHeadView.tv_Time.setText(detailBean.getReleaseTime());
            if (detailBean.getBrokeNewsType() != null){
                exposureHeadView.tv_Type.setText("#" + detailBean.getBrokeNewsType().getName() + "");
            }
            exposureHeadView.tv_Praise.setText("" + detailBean.getPraiseTimes() + "");
            exposureHeadView.tv_Title.setText("主题：" + detailBean.getTitle());
            exposureHeadView.tv_Content.setText("内容：" + detailBean.getContent());
            if (!BaseUtil.isEmpty(detailBean.getAddress())) {
                exposureHeadView.tv_Location.setText(detailBean.getAddress());
            }else {
                exposureHeadView.tv_Location.setVisibility(View.GONE);
            }
            exposureHeadView.tv_Preview.setText("" + detailBean.getReadTimes() + "");
            if (detailBean.getFiles() != null && detailBean.getFiles().size() > 0) {
                ImageAdapter adapter = new ImageAdapter(this, R.layout.item_image, detailBean.getFiles());
                exposureHeadView.imgListView.setAdapter(adapter);
            } else {
                exposureHeadView.imgListView.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void voidView(String message) {
        ToastUtils.showToast(this, message);
    }

    /**
     * 第一次加载
     */
    public void onRefresh() {
        currentPager = 1;
        loadReplyList();
    }

    private void loadReplyList() {
        exposurePest.replyExposureList(exposureID, currentPager, 3);
    }


}
